package com.sample.sampleproj;

import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.R.string;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
  

public class SampleprojActivity extends Activity implements OnClickListener {
   
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);// activity loads its UI from the XML file main.xml. 
       
        setContentView(R.layout.main); //to display it as the content for the Activity UI. 

        final Button btn1 = (Button) findViewById(R.id.Search);//R.id.button_id);
        btn1.setText("Search");
        btn1.setOnClickListener(this);
        Spinner spinner = (Spinner) findViewById(R.id.spinner);//Drop-Down menu created in the android app
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.planets_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);//To display all the options available in the drop-down menu ..the option are given Strings.xml
        spinner.setAdapter(adapter);
        
        
	}
 public void onClick(View v){
	 final EditText addr= (EditText) findViewById(R.id.addrvalue);
	 int x=addr.getText().length();
	 if(x==0)
	    {
	 final TextView text= (TextView) findViewById(R.id.txt);
	 text.setText("Detecting the current Geo Location...");
        	 
	    }
        		LocationManager locationManager;
        	    double lati,longi;
        	   // final EditText addr= (EditText) findViewById(R.id.addrvalue);
        	// int x=addr.getText().length();
        	  //  Toast.makeText(this, addr.getText(), Toast.LENGTH_LONG).show();
        	   
        	    String location_context = Context.LOCATION_SERVICE;
        	    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        	       //locationManager.requestLocationUpdates("gps", 1000, 1,(LocationListener) this );
        	       // testProviders();
        	       //(LocationManager)getSystemService(Context.LOCATION_SERVICE)
        	   
        	    
        	     TextView tv = new TextView(this);
        	     StringBuilder sb = new StringBuilder("Enabled Providers:");
        	       // LocationManager locationManager;
        	      Criteria crit = new Criteria();
        	      crit.setAccuracy(Criteria.ACCURACY_FINE);
        	      String providers = locationManager.getBestProvider(crit, true);
				  List<String> provider = locationManager.getProviders(true);
				  System.out.println("No providers"+provider);
        	        //for (String prov : provider) 
        	        //{
        	        locationManager.requestLocationUpdates(providers, 1, 1,new LocationListener()
        	           {
        	              public void onLocationChanged(Location location)
        	              {
        	              double lati = location.getLatitude();
          	              double longi= location.getLongitude();
          	              System.out.println("latitude"+lati+"longitude"+longi);
          	                     
        	              }
        	              public void onProviderDisabled(String provider){}
        	              public void onProviderEnabled(String provider){}
        	              public void onStatusChanged(String provider, int status,
        	              Bundle extras){}
        	           });
        	              
        	           Location location = locationManager.getLastKnownLocation(providers);
        	           System.out.println("the loction is"+location);
        	           if (location != null)
        	           {
        	                lati = location.getLatitude();
        	                longi= location.getLongitude();
        	                     
        	               if(x==0){      
        	                final TextView latitude= (TextView) findViewById(R.id.Latitude);
        	                latitude.setText("Current Latitude: "+String.valueOf(lati));
        	                    
        	                final TextView longitude= (TextView) findViewById(R.id.Longitude);
        	                longitude.setText("Current Longitude: "+String.valueOf(longi));
        	                    
        	               }// lati=lat;
        	                     //longi=lng;  
        	                    //Geocoder gcd = new Geocoder(SampleprojActivity.this, Locale.getDefault());
        	                    //List<Address> addresses;
        	                    //try {// System.out.println("Adresses"+addresses.get(0));
        	                      //     addresses = gcd.getFromLocation(lati, longi, 1);
        	                        //    if (addresses.size() > 0) 
        	                          //  	System.out.println("Adresses"+addresses.get(0));
        	                            //System.out.println(addresses.get(0).getLocality());
        	                            //Toast.makeText(SampleprojActivity.this, "hi", 5000).show();
        	                          //} catch (IOException e)
        	                            // {

        	                              // Toast.makeText(SampleprojActivity.this, "hi exception", 5000).show();
        	                               //e.printStackTrace();
      	                                   //}
                          } 
        	              else 
        	              {
        	                  sb.append("No Location");
        	              }
        	           
        	        tv.setText(sb);
       
       		   try{
        			Spinner spinner = (Spinner) findViewById(R.id.spinner);
        			
        			 ArrayList<BasicNameValuePair> nvp= new ArrayList<BasicNameValuePair>(3);//array to store values 
                     nvp.add(new BasicNameValuePair("Cat", String.valueOf(spinner.getSelectedItem())));//Converts the form value to a string
                     nvp.add(new BasicNameValuePair("place",String.valueOf(addr.getText())));
                     nvp.add(new BasicNameValuePair("latitude", String.valueOf(location.getLatitude())));
                     nvp.add(new BasicNameValuePair("longitude",String.valueOf(location.getLongitude())));
        			URL url = new URL("http://204.232.203.10/mobile-db/User1.php"); 
        			     url.openConnection(); 
        		     HttpClient httpclient = new DefaultHttpClient();
        		     HttpPost httppost = new HttpPost("http://204.232.203.10/mobile-db/User1.php");
        		     httppost.setEntity(new UrlEncodedFormEntity(nvp)); //to send namevaluepair array values from the android form to User1.php
        		     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();//To avoid the networkonmainthreadException(supposed To send http request asynchronusly ,if not the operation is done on the main thread and an exception is thrown)
        		     StrictMode.setThreadPolicy(policy);
        		     
        		   String rest= httpclient.execute(httppost, finishTranslation);
        		   System.out.println(rest);
        		   Document doc=XMLfunctions.XMLfromString(rest);
        		  // NodeList nodes = doc.getElementsByTagName("Park");
        		   
        		   //String x="Hello Android";
        		   Intent intent = new Intent(SampleprojActivity.this,ListViewActivity.class);
        		   
           	       intent.putExtra("rest",rest);
        		  // startActivity(intent);
        		   startActivityForResult(intent,1);
        		  
        	      
        		     }catch(Exception e){
        		         Log.e("log_tag", "Error in http connection"+e.toString());
        		         Toast.makeText(this, "ERROR IN CONN", Toast.LENGTH_LONG).show();
        		    }
         
         }
 
        		final ResponseHandler<String> finishTranslation = new ResponseHandler<String>() 

        	{
        		    public String handleResponse(
        		            HttpResponse response) throws ClientProtocolException, IOException 
        		    {
        		    	Log.e("log_tag","After response handling");
        		    	HttpEntity entity = response.getEntity();//gets the response from User1.php
        		        if (entity != null) 
        		        {  
        		            String res = EntityUtils.toString(entity);//Converts the response to a String
        		            System.out.println(res);
        		            System.out.println("ParsingXML");
                			
                		      return res;
        		        } 
        		        else{
        		        	return null;
        		        }
        		    }
        	
						
        				
        		};

}
  
